﻿using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace FurionApiDemo.Core.Entity
{
    /// <summary>
    /// 用户角色表
    /// </summary>
    [Table("UserRole")]
    public class SysUserRole : IEntity, IEntityTypeBuilder<SysUserRole>
    {
        /// <summary>
        /// 用户Id
        /// </summary>
        [Comment("用户Id")]
        [Required]
        public long UserId { get; set; }

        /// <summary>
        /// 一对一引用（系统用户）
        /// </summary>
        public virtual SysUser SysUser { get; set; }

        /// <summary>
        /// 角色Id
        /// </summary>
        [Comment("角色Id")]
        [Required]
        public long RoleId { get; set; }

        /// <summary>
        /// 一对一引用（系统角色）
        /// </summary>
        public virtual SysRole SysRole { get; set; }

        public void Configure(EntityTypeBuilder<SysUserRole> entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder.HasKey(t => new
            {
                t.RoleId,
                t.UserId
            });
            entityBuilder.HasOne(t => t.SysRole)
                .WithMany(t => t.SysUserRoles)
                .HasForeignKey(t => t.RoleId)
                .OnDelete(DeleteBehavior.ClientSetNull);
            entityBuilder.HasOne(t => t.SysUser)
                .WithMany(t => t.SysUserRoles)
                .HasForeignKey(t => t.UserId)
                .OnDelete(DeleteBehavior.ClientSetNull);
        }
    }
}
